var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');
var EventProxy = require('eventproxy');
var _ = require('lodash');
var formidable = require('formidable');
var fs = require('fs');
var moment = require("moment");

//met一周直播
var liveController = {
    getListPage: function (req, res) {
        var nowTime = util.getNowTime();
        var paramT = {};
        var params = {};
        var liveSql = "select *,case when end_time > '" + nowTime + "' then 1 else 0 end as isClose from lm_live where 1=1 "
        var midSql = "";
        if (req.query.sort != undefined) {
            midSql += " and sort = " + parseInt(req.query.sort);
            params.sort = parseInt(req.query.sort);
        }
        if (req.query.pTitle != undefined) {
            midSql += " and  (title like '%" + req.query.pTitle + "%' or expert_name like '%" + req.query.pTitle + "%')";
            params["$or"] = [{ "title": { "$like": '%' + req.query.pTitle + '%' } }, { "expertName": { "$like": '%' + req.query.pTitle + '%' } }]
        }
        liveSql += midSql;
        paramT.where = params;

        liveSql += " order by start_time DESC ";
        var page = parseInt(req.query.page);
        if (req.query.page != undefined && req.query.rows != undefined) {
            var rows = parseInt(req.query.rows);
            liveSql += " limit " + page + "," + rows;
        }
        var ep = new EventProxy();

        ep.all('total', 'result', function (total, result) {
            res.json({ 'success': true, 'msg': '查询成功！', 'total': total, 'page': page, 'result': result });
        })

        seq.sequelize.query(liveSql).spread(function (result) {
            ep.emit('result', result);
        }).catch(function (err) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(err);
        })
        seq.liveModule.count(paramT).then(function (count) {
            ep.emit('total', count);
        }).catch(function (err) {
            res.json({ 'success': false, 'msg': '查询总条数失败' });
            console.log(err);
        });

    },
    getLiveById: function (req, res) {
        if (_.isEmpty(req.params) || !_.hasIn(req.params, 'id') || _.isEmpty(req.params.id)) {
            res.json({ 'success': false, 'msg': 'ID未传参！' });
        } else {
            seq.liveModule.findOne({ where: req.params }).then(function (result) {
                res.json({ 'success': true, 'msg': '查询成功！', 'result': result });
            }).catch(function (err) {
                res.json({ 'success': false, 'msg': '查询失败' });
                console.log(err);
            });
        }
    },
    addLives: function (req, res) {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/data/expertImg";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                if (_.hasIn(files, 'expertHeadImg') && files.expertHeadImg.name != "") {
                    var imgType = files.expertHeadImg.name.split(".");
                    files.expertHeadImg.name = "liveExpert_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                    fs.renameSync(files.expertHeadImg.path, form.uploadDir + "/" + files.expertHeadImg.name);
                    fields.expertHeadImg = files.expertHeadImg.name;
                }
                fields.id = util.getUUID();
                fields.createTime = util.getNowTime();
                fields.topTime = util.getNowTime();
                var sort = parseInt(fields.sort);
                seq.liveModule.create(fields).then(function (result) {
                    if (sort == 101) {
                        res.redirect(util.getIP() + 'metLive/metLiveMeetList.html');
                    } else {
                        res.redirect(util.getIP() + 'metLive/metLiveExpertList.html');
                    }

                })
            });
        } else {
            console.log("请求方式不正确");
        }
    },
    updateLives: function (req, res) {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/data/expertImg";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var paramT = {};
                if (_.hasIn(files, 'expertHeadImg') && files.expertHeadImg.name != "") {
                    var imgType = files.expertHeadImg.name.split(".");
                    files.expertHeadImg.name = "liveExpert_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                    fs.renameSync(files.expertHeadImg.path, form.uploadDir + "/" + files.expertHeadImg.name);
                    fields.expertHeadImg = files.expertHeadImg.name;
                }
                paramT.where = req.params;
                var sort = parseInt(fields.sort);
                seq.liveModule.update(fields, paramT).then(function (result) {
                    if (sort == 101) {
                        res.redirect(util.getIP() + 'metLive/metLiveMeetList.html');
                    } else {
                        res.redirect(util.getIP() + 'metLive/metLiveExpertList.html');
                    }
                })
            });
        } else {
            console.log("请求方式不正确");
        }
    },
    deleteLive: function (req, res) {
        var params = req.query.params;
        var arr = params.split(",");
        var paramT = [arr];
        seq.liveModule.destroy({ 'where': { 'id': paramT } }).then(function (results) {
            res.json({ "success": true, "msg": "删除成功", "rows": results });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    }
}
module.exports = liveController;